/* import getFilenameFromUrl from './get-filename-from-url'
import * as file from './file' */

/**
 *  功能：文件下载
 * @param {String} url 下载的URL地址
 * @param {String} name 下载名称
 * @param {String} urlIsText url为文本内容
 */
export default async function (url, filename, params, progress, success) {
  if (!filename) {
    return
  }
  var xhr = new XMLHttpRequest()
  xhr.open('POST', url, true)
  // 监听进度事件
  xhr.addEventListener(
    'progress',
    function (evt) {
      if (progress) {
        try {
          progress.call(evt)
        } catch (e) { }
      }
    },
    false
  )

  xhr.responseType = 'blob'
  xhr.setRequestHeader(
    'Content-Type',
    'application/x-www-form-urlencoded; charset=UTF-8'
  )

  var paramsStr = ''
  if (params) { for (var key in params) paramsStr += '&' + key + '=' + params[key] }
  if (paramsStr) paramsStr = paramsStr.substring(1)
  xhr.send(paramsStr)
  return new Promise((resolve, reject) => {
    xhr.onreadystatechange = function () {
      console.log('xhr.readyState:', xhr.readyState, 'xhr.status:', xhr.status)
      if (xhr.readyState === 4 && xhr.status === 200) {
        console.log('loaded..')
        window.$ui.msg({ type: 'success', message: `${filename}文件下载成功` })
        if (typeof window.chrome !== 'undefined') {
          // Chrome version
          var link = document.createElement('a')
          link.href = window.URL.createObjectURL(xhr.response)
          link.download = filename
          link.click()
          resolve()
        } else if (typeof window.navigator.msSaveBlob !== 'undefined') {
          // IE version
          var blob = new Blob([xhr.response], {
            type: 'application/force-download'
          })
          window.navigator.msSaveBlob(blob, filename)
        } else {
          // Firefox version
          var file = new File([xhr.response], filename, {
            type: 'application/force-download'
          })
          window.open(URL.createObjectURL(file))
          resolve()
        }
        if (success) {
          try {
            success.call(xhr)
          } catch (e) {
            window.$ui.msg({ type: 'error', message: `${filename}下载失败` })
          }
        }
      } else if (xhr.readyState === 4 && xhr.status === 404) {
        window.$ui.msg({ type: 'error', message: `${filename}下载失败,文件不存在!` })
        reject(new Error('下载失败,文件不存在!'))
      } else if (xhr.readyState === 2 && xhr.status === 200) {
        window.$ui.msg({ type: 'info', message: `${filename}文件下载中...` })
      }
    }
  })
}
